//
//  HBTableViewHeaderView.m
//  FMSManager
//
//  Created by hongbao.cui on 15-1-8.
//  Copyright (c) 2015年 hongbao.cui. All rights reserved.
//

#import "HBTableViewHeaderView.h"
#import "ApplicationUtils.h"
@implementation HBUIImageView
-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.alpha = 0.8;
        self.backgroundColor = [UIColor blackColor];
        
        self.userInteractionEnabled = YES;
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.minimumZoomScale = 1.0;
        _scrollView.maximumZoomScale = 3.0;
        [_scrollView setDelegate:self];
        [self addSubview:_scrollView];
        
        _tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];
        [self addGestureRecognizer:_tapGestureRecognizer];
        
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        
        [_scrollView addSubview:_imageView];
        
        UITapGestureRecognizer * doubleTap    = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fakeDoubleTapGestureHandler:)];
        [doubleTap setNumberOfTapsRequired:2];
        [_tapGestureRecognizer requireGestureRecognizerToFail:doubleTap];  //加入这一行就不会出现这个问题
        [self addGestureRecognizer:doubleTap];
        
        UIPinchGestureRecognizer* pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchView:)];
        [self addGestureRecognizer:pinchGesture];
    }
    return self;
}
-(void)setImage:(UIImage *)image{
    if (_imageView) {
        CGFloat width = image.size.width;
        CGFloat height = image.size.height;
        CGFloat newWidth = 0;
        CGFloat newHeight = 0;
        if (width>=FMSCREENWIDTH&&height<=FMSCREENHEIGHT) {
            newWidth = FMSCREENWIDTH;
            newHeight =height;
        }else if(width<FMSCREENWIDTH&&height<=FMSCREENHEIGHT){
            newWidth = width;
            newHeight =height;
        }else if (width>=FMSCREENWIDTH&&height>FMSCREENHEIGHT){
            newWidth = FMSCREENWIDTH;
            newHeight =FMSCREENHEIGHT;
        }
        [_imageView setFrame:CGRectMake(0, 0, newWidth, newHeight)];
        _scrollView.contentSize = CGSizeMake(image.size.width, image.size.height);
        _scrollView.frame = self.bounds;
        _imageView.center = _scrollView.center;
        [_imageView setImage:image];
    }
}
-(void)fakeDoubleTapGestureHandler:(UITapGestureRecognizer *)gesture{
    if (!tapped) {
//        CGPoint tapPoint = [_tapGestureRecognizer locationOfTouch:0 inView:_tapGestureRecognizer.view];
//        CGRect zoomRect = [self zoomRectForScrollView:self.scrollView withScale:2.0f withCenter:tapPoint];
//        [self.scrollView zoomToRect:zoomRect animated:YES];
        [self.scrollView setZoomScale:3.0f animated:YES];
        tapped = YES;
    } else {
        [self.scrollView setZoomScale:1.0f animated:YES];
        tapped = NO;
    }
}
- (void)scrollViewEnd
{
    if (_scrollView.zoomScale < 1.0) {
        [self.scrollView setZoomScale:1.0 animated:YES];
        _scrollView.contentOffset = CGPointMake(0, 0);
    } else if (_scrollView.zoomScale > 3.0) {
        [_scrollView setZoomScale:3.0 animated:YES];
    }
}
-(void)handlePinchView:(UIPinchGestureRecognizer *)gesture{
    if ([gesture state] == UIGestureRecognizerStateBegan) {
        imageHWScale = _imageView.image.size.height/_imageView.image.size.width;
        beganScale = _scrollView.zoomScale;
    }
    CGFloat scale = beganScale * gesture.scale;
    [_scrollView setZoomScale:scale];
    
    if ([gesture state] == UIGestureRecognizerStateEnded) {
        [self scrollViewEnd];
    }
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    [self scrollViewEnd];
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{

}
-(void)tapRecognized:(id)sender {
    [self removeFromSuperview];
}

/* Apple's utility method that converts a specified scale and center point to a rectangle for zooming */
- (CGRect)zoomRectForScrollView:(UIScrollView *)scrollView withScale:(float)scale withCenter:(CGPoint)center {
    CGRect zoomRect;
    zoomRect.size.height = scrollView.frame.size.height / scale;
    zoomRect.size.width = scrollView.frame.size.width / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
    return zoomRect;
}
@end;
@implementation HBTableViewHeaderView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
-(void)answerBtnClicked:(UIButton *)sender{
    if (self.simpleBlock) {
        self.simpleBlock(self);
    }
}
-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];

        int x,y,w,h;
        x = 10;y=2;w=FMSCREENWIDTH-20;h = 30;
        if (!_bgImageView) {
            _bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, w, h)];
            [_bgImageView setBackgroundColor:[UIColor clearColor]];
            [self addSubview:_bgImageView];
        }
        if (!_lineImageView) {
            _lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, y+h, FMSCREENWIDTH-40, 1)];
            [_lineImageView setImage:[ApplicationUtils getLocalImage:@"st_line@2x"]];
            [_lineImageView setHidden:YES];
            [self addSubview:_lineImageView];
        }
        _typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, FMSCREENWIDTH-20, 20)];
//        [_typeLabel setText:@"1111111111111111"];
        [_typeLabel setNumberOfLines:0];
        [_typeLabel setLineBreakMode:NSLineBreakByCharWrapping];
        [_typeLabel setBackgroundColor:[UIColor clearColor]];
        [_typeLabel setTextAlignment:NSTextAlignmentLeft];
        [_typeLabel setFont:[UIFont systemFontOfSize:15.0]];
        [_typeLabel setTextColor:[UIColor colorWithRed:0.0/255.0 green:181.0/255.0 blue:167.0/255.0 alpha:1.0]];
//        _typeLabel.layer.borderColor = [UIColor colorWithRed:0.0/255.0 green:181.0/255.0 blue:167.0/255.0 alpha:1.0].CGColor;
//        _typeLabel.layer.borderWidth = 0.5;
//        _typeLabel.layer.cornerRadius = 3.0;
        [self addSubview:_typeLabel];
        
        if (!_titleWebView) {
            _titleWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0,_typeLabel.frame.size.height,w-25,h)];
            [_titleWebView setBackgroundColor:[UIColor clearColor]];
            [_titleWebView setDelegate:self];
            [_bgImageView addSubview:_titleWebView];
            [_bgImageView setUserInteractionEnabled:NO];
            [_titleWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
            [self addSubview:_bgImageView];
        }
//        NSURL *url = [NSURL URLWithString:@"http://121.41.95.209:5080/MathJax/MathJax.js?config=MML_HTMLorMML-full"];
//        NSString *fileStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
//        [_titleWebView stringByEvaluatingJavaScriptFromString:fileStr];
//        if (!_answerBtn) {
//            _answerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//            [_answerBtn setFrame:CGRectMake(FMSCREENWIDTH-40, y+h, 21.0, 20.0)];
//            [_answerBtn setBackgroundImage:[UIImage imageNamed:@"HomeKeyPointCellExerciseButtonPressed.png"] forState:UIControlStateNormal];
//            [_answerBtn setBackgroundImage:[UIImage imageNamed:@"HomeKeyPointCellExerciseButtonPressed.png"] forState:UIControlStateHighlighted];
//            [_bgImageView addSubview:_answerBtn];
//            [_answerBtn addTarget:self action:@selector(answerBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
//            [_answerBtn setHidden:YES];
//            [self addSubview:_answerBtn];
//        }
        // Add gesture
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fakeTapGestureHandler:)];
        
        [self addGestureRecognizer:tapGestureRecognizer];
    }
    return self;
}
-(void)fakeTapGestureHandler:(UITapGestureRecognizer *)gesture{
    int scrollPositionY = [[_titleWebView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue];
    int scrollPositionX = [[_titleWebView stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] intValue];
    //    int displayWidth = [[_anylisewebView stringByEvaluatingJavaScriptFromString:@"window.outerWidth"] intValue];
    CGFloat scale =1.0; //_anylisewebView.frame.size.width / displayWidth;
    
    CGPoint pt = [gesture locationInView:_titleWebView];
    pt.x *= scale;
    pt.y *= scale;
    pt.x += scrollPositionX;
    pt.y += scrollPositionY;
    
    NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", pt.x, pt.y];
    NSString * tagName = [_titleWebView stringByEvaluatingJavaScriptFromString:js];
    FMSCHBLog(@"tagName =%@", tagName);
    if ([tagName isEqualToString:@"img"]||[tagName isEqualToString:@"IMG"]) {
        NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];
        NSString *urlToSave = [_titleWebView stringByEvaluatingJavaScriptFromString:imgURL];
        NSString *fileName =  [[urlToSave componentsSeparatedByString:@"/"] lastObject];
        if ([fileName isEqualToString:@"st_Options_mark_001.png"]||[fileName isEqualToString:@"st_Options_mark_001@2x.png"]||[fileName isEqualToString:@"st_Options_mark_002@2x.png"]||[fileName isEqualToString:@"st_Options_mark_002.png"]) {
            return;
        }
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *docDir = [[paths objectAtIndex:0] stringByAppendingString:[NSString stringWithFormat:@"/Paper/image/%@",fileName]];
        NSURL *fileURL = [NSURL fileURLWithPath:docDir];
        UIImage *image = [UIImage imageWithData:[NSData
                                                 dataWithContentsOfURL:fileURL]];
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        CGPoint point = [keyWindow convertPoint:pt fromView:self];
        
        HBUIImageView *imageView = [[HBUIImageView alloc] initWithFrame:CGRectMake(point.x, point.y, 0, 0)];
        [keyWindow addSubview:imageView];
        [UIView animateWithDuration:0.5 animations:^{
            [imageView setFrame:CGRectMake(0, 0, FMSCREENWIDTH, FMSCREENHEIGHT)];
        } completion:^(BOOL finished) {
            if (finished) {
                [imageView setImage:image];
            }
        }];
    }
}
-(void)setDataReload:(NSDictionary *)dict WithQuestionCount:(NSInteger)count {
    NSString *orderIdStr =[dict objectForKey:@"orderid"];
    NSString *titleStr =[dict objectForKey:@"content"];
    NSString *qtype = [dict objectForKey:@"qtype"];
    NSString *qtype_name = [dict objectForKey:@"qtype_name"];
//    qtype_name = [qtype_name substringWithRange:NSMakeRange(0, 1)];
    if ([qtype isEqualToString:@"4"]) {//简答题
        [_answerBtn setHidden:NO];
//        [_typeLabel setText:@"简"];
    }else if([qtype isEqualToString:@"1"]){
//        [_typeLabel setText:@"单"];
    }else if([qtype isEqualToString:@"2"]){
//        [_typeLabel setText:@"多"];
    }else if([qtype isEqualToString:@"3"]){
//        [_typeLabel setText:@"判"];
    }
    if (qtype_name && ![qtype_name isEqualToString:@""]) {
        [_typeLabel setText:qtype_name];
    }
    else{
//        [_typeLabel removeFromSuperview];
//        _typeLabel = nil;
    }
    NSString *HTMLData =nil;
    if (_isHeaderView) {
        if (count==1) {
            HTMLData = [NSString stringWithFormat:@"%@",titleStr];
        }else{
            HTMLData = [NSString stringWithFormat:@"(%@)%@",orderIdStr,titleStr];
        }
    }else{
        if (count==1) {
            HTMLData = [NSString stringWithFormat:@"%@",titleStr];
        }else{
            HTMLData = [NSString stringWithFormat:@"%@.%@",orderIdStr,titleStr];
        }
    }
    NSString *path = [FMPAPERSAVE_PATH stringByAppendingPathComponent:@"image"];
    NSURL  *url = [NSURL fileURLWithPath:path];
    [_titleWebView loadHTMLString:HTMLData baseURL:url];
    
    NSDictionary *dict_1 = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
    CGRect boundingRect = [qtype_name boundingRectWithSize:CGSizeMake(FMSCREENWIDTH-40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict_1 context:nil];
    [_typeLabel setFrame:CGRectMake(10, 0,FMSCREENWIDTH-40, boundingRect.size.height)];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_titleWebView setFrame:CGRectMake(_titleWebView.frame.origin.x, _typeLabel.frame.size.height+_typeLabel.frame.origin.y, _typeLabel.frame.size.width,_titleWebView.scrollView.contentSize.height)];
    [_bgImageView setFrame:CGRectMake(_bgImageView.frame.origin.x, _bgImageView.frame.origin.y, _bgImageView.frame.size.width, _titleWebView.scrollView.contentSize.height)];
    [_lineImageView setFrame:CGRectMake(_bgImageView.frame.origin.x+10, _bgImageView.frame.origin.y+_titleWebView.scrollView.contentSize.height, _bgImageView.frame.size.width-20, 1)];
    
    [_answerBtn setFrame:CGRectMake(FMSCREENWIDTH-40, _bgImageView.frame.origin.y+_titleWebView.scrollView.contentSize.height-25, 21, 20)];

    [_lineImageView setHidden:NO];
    self.frame = CGRectMake(0, 0, FMSCREENWIDTH, _titleWebView.frame.origin.y+_titleWebView.frame.size.height+10);
    [NSThread sleepForTimeInterval:0.1];
    
    
    if (_delegate&&[_delegate respondsToSelector:@selector(HBTableViewHeaderView:webViewDidFinishLoad:)]) {
        [_delegate HBTableViewHeaderView:self webViewDidFinishLoad:webView];
    }
    
    
//    [_titleWebView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
//     "script.type = 'text/javascript';"
//     "script.text = function ResizeImages(){"
//     "var myimg,oldwidth;"
//     "var maxwidth=380;" //缩放系数
//     "for(i=0;i <document.images.length;i++){"
//     "myimg = document.images;"
//     "if(myimg.width > maxwidth){"
//     "oldwidth = myimg.width;"
//     "myimg.width = maxwidth;"
//     "myimg.height = myimg.height * (maxwidth/oldwidth);"
//     "}"
//     "alert(\"myimg.width\"+myimg);"
//     "alert(\"myimg.height\"+myimg.height);"
//     "}"
//     
//     "};"
//     "document.getElementsByTagName('head')[0].appendChild(script);"];
//    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}
-(void)dealloc{
    [_titleWebView.scrollView removeObserver:self forKeyPath:@"contentSize"];
    _titleWebView = nil;
    _bgImageView = nil;
    _lineImageView = nil;
    if (self.simpleBlock) {
        self.simpleBlock = nil;
    }
    _titleWebView.delegate = nil;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    [_titleWebView setFrame:CGRectMake(_titleWebView.frame.origin.x,  _typeLabel.frame.size.height+_typeLabel.frame.origin.y, _typeLabel.frame.size.width,_titleWebView.scrollView.contentSize.height)];
    [_bgImageView setFrame:CGRectMake(_bgImageView.frame.origin.x, _bgImageView.frame.origin.y, _bgImageView.frame.size.width, _titleWebView.scrollView.contentSize.height)];
    [_lineImageView setFrame:CGRectMake(_titleWebView.frame.origin.x+10, _titleWebView.frame.origin.y+_titleWebView.frame.size.height+10, _titleWebView.frame.size.width-20, 1)];
    
    [_answerBtn setFrame:CGRectMake(FMSCREENWIDTH-40, _bgImageView.frame.origin.y+_titleWebView.scrollView.contentSize.height-25, 21, 20)];
    
    [_lineImageView setHidden:NO];
    self.frame = CGRectMake(0, 0, FMSCREENWIDTH, _lineImageView.frame.origin.y+_lineImageView.frame.size.height+10+_typeLabel.frame.size.height);
}
@end
